package org.mall.modules.mq.pay;

/***
 *@author yinxucun
 *@date 2020-01-05 16:54
 */

import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.mall.common.util.json.JacksonUtils;
import org.mall.modules.pojo.pay.message.PayTransactionExtensionCloseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 消息消费监听
 */
@Slf4j
@Component
public class TransactionCloseMsgListener implements MessageListenerConcurrently {
    @Autowired
    @Qualifier("transactionService")
    WxPayService wxPayService;
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
        if (CollectionUtils.isEmpty(list)){
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        MessageExt messageExt = list.get(0);
        int reConsume = messageExt.getReconsumeTimes();
        PayTransactionExtensionCloseDTO closeDTO= (PayTransactionExtensionCloseDTO) JacksonUtils.parseObject(new String(messageExt.getBody()), PayTransactionExtensionCloseDTO.class);

        // 消息已经重试了3次，如果不需要再次消费，则返回成功
        if(reConsume >=4){
            log.error("微信订单关闭尝试了{}次,不再进行尝试关闭，微信退款订单号:{}转手动关闭",reConsume-1,closeDTO.getTransactionCode());
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        try {
            wxPayService.closeOrder(closeDTO.getTransactionCode());
        } catch (WxPayException e) {
            if ("SYSTEMERROR".equals(e.getErrCode())){
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        }

        ;
        // 消息消费成功
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}

